package online.flowerinsnow.minecraft.bukkit.testffa.manager;

import online.flowerinsnow.minecraft.bukkit.testffa.Main;
import online.flowerinsnow.minecraft.bukkit.testffa.stats.PlayerStatsImpl;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class StatsManagerImpl implements IStatsManager {
    @NotNull
    public Map<Player, PlayerStatsImpl> stats = new HashMap<>();

    @Override
    public @Nullable PlayerStatsImpl getOnlinePlayerStats(@NotNull Player player) {
        return stats.get(player);
    }

    @Override
    public @Nullable PlayerStatsImpl getOfflinePlayerStats(@NotNull UUID uuid) {
        try (Statement statement = SQLManager.getConnection().createStatement();
             ResultSet res = statement.executeQuery("SELECT * from `ffastats` WHERE `uuid` = '" + uuid.toString() + "'")) {
            if (res.next()) { // 判断这个玩家的数据是否存在
                return new PlayerStatsImpl(uuid, res.getInt("kill"), res.getInt("death"));
            } else {
                return null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public PlayerStatsImpl loadPlayerStats(@NotNull Player player) {
        PlayerStatsImpl stats = getOfflinePlayerStats(player.getUniqueId());
        if (stats == null) {
            try (Statement statement = SQLManager.getConnection().createStatement()) {
                statement.executeUpdate("INSERT INTO `ffastats` (`uuid`) values ('" + player.getUniqueId().toString() + "')");
                stats = new PlayerStatsImpl(player.getUniqueId(), 0, 0);
            } catch (SQLException e) {
                e.printStackTrace();
                Bukkit.getScheduler().runTask(Main.getInstance(), () -> player.kickPlayer("§c您的数据加载失败 若该问题持续发生 请联系管理员"));
            }
        }
        this.stats.put(player, stats);
        return stats;
    }
}
